home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / wadllib / README.txt < prev   
Text File  |  2009-08-25  |  20KB  |  556 lines

  1. ..
  2.    Copyright (C) 2008-2009 Canonical Ltd.
  3.  
  4.    This file is part of wadllib.
  5.  
  6.    wadllib is free software: you can redistribute it and/or modify it under
  7.    the terms of the GNU Lesser General Public License as published by the
  8.    Free Software Foundation, version 3 of the License.
  9.  
  10.    wadllib is distributed in the hope that it will be useful, but WITHOUT ANY
  11.    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12.    FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
  13.    more details.
  14.  
  15.    You should have received a copy of the GNU Lesser General Public License
  16.    along with wadllib. If not, see <http://www.gnu.org/licenses/>.
  17.  
  18. wadllib
  19. *******
  20.  
  21. An Application object represents a web service described by a WADL
  22. file.
  23.  
  24.    >>> import os
  25.    >>> import sys
  26.    >>> import pkg_resources
  27.    >>> from wadllib.application import Application
  28.  
  29. The first argument to the Application constructor is the URL at which
  30. the WADL file was found. The second argument may be raw WADL markup.
  31.  
  32.    >>> wadl_string = pkg_resources.resource_string(
  33.    ...     'wadllib.tests.data', 'launchpad-wadl.xml')
  34.    >>> wadl = Application("http://api.launchpad.dev/beta/", wadl_string)
  35.  
  36. Or the second argument may be an open filehandle containing the markup.
  37.  
  38.    >>> def application_for(filename, url="http://www.example.com/"):
  39.    ...    wadl_stream = pkg_resources.resource_stream(
  40.    ...    'wadllib.tests.data', filename)
  41.    ...    return Application(url, wadl_stream)
  42.    >>> wadl = application_for("launchpad-wadl.xml",
  43.    ...                        "http://api.launchpad.dev/beta/")
  44.  
  45.  
  46. ===============
  47. Link navigation
  48. ===============
  49.  
  50. The preferred technique for finding a resource is to start at one of
  51. the resources defined in the WADL file, and follow links. This code
  52. retrieves the definition of the root resource.
  53.  
  54.    >>> service_root = wadl.get_resource_by_path('')
  55.    >>> service_root.url
  56.    'http://api.launchpad.dev/beta/'
  57.    >>> service_root.type_url
  58.    '#service-root'
  59.  
  60. The service root resource supports GET.
  61.  
  62.    >>> get_method = service_root.get_method('get')
  63.    >>> get_method.id
  64.    'service-root-get'
  65.  
  66.    >>> get_method = service_root.get_method('GET')
  67.    >>> get_method.id
  68.    'service-root-get'
  69.  
  70. If we want to invoke this method, we send a GET request to the service
  71. root URL.
  72.  
  73.    >>> get_method.name
  74.    'get'
  75.    >>> get_method.build_request_url()
  76.    'http://api.launchpad.dev/beta/'
  77.  
  78. The WADL description of a resource knows which representations are
  79. available for that resource. In this case, the server root resource
  80. has a a JSON representation, and it defines parameters like
  81. 'people_collection_link', a link to a list of people in Launchpad. We
  82. should be able to use the get_parameter() method to get the WADL
  83. definition of the 'people_collection_link' parameter and find out more
  84. about it--for instance, is it a link to another resource?
  85.  
  86.    >>> link_name = 'people_collection_link'
  87.    >>> link_parameter = service_root.get_parameter(link_name)
  88.    Traceback (most recent call last):
  89.    ...
  90.    NoBoundRepresentationError: Resource is not bound to any representation, and no media media type was specified.
  91.  
  92. Oops. The code has no way to know whether 'people_collection_link' is
  93. a parameter of the JSON representation or some other kind of
  94. representation. We can pass a media type to get_parameter and let it
  95. know which representation the parameter lives in.
  96.  
  97.    >>> link_parameter = service_root.get_parameter(
  98.    ...     link_name, 'application/json')
  99.    >>> link_parameter.get_value()
  100.    Traceback (most recent call last):
  101.    ...
  102.    NoBoundRepresentationError: Resource is not bound to any representation.
  103.  
  104. Oops again. The parameter is available, but it has no value, because
  105. there's no actual data associated with the resource. The browser can
  106. look up the description of the GET method to make an actual GET
  107. request to the service root, and bind the resulting representation to
  108. the WADL description of the service root.
  109.  
  110. You can't bind just any representation to a WADL resource description.
  111. It has to be of a media type understood by the WADL description.
  112.  
  113.    >>> service_root.bind('<html>Some HTML</html>', 'text/html')
  114.    Traceback (most recent call last):
  115.    ...
  116.    UnsupportedMediaTypeError: This resource doesn't define a representation for media type text/html
  117.  
  118. The WADL description of the service root resource has a JSON
  119. representation. Here it is.
  120.  
  121.    >>> json_representation = service_root.get_representation_definition(
  122.    ...     'application/json')
  123.    >>> json_representation.media_type
  124.    'application/json'
  125.  
  126. We already have a WADL representation of the service root resource, so
  127. let's try binding it to that JSON representation. We use test JSON
  128. data from a file to simulate the result of a GET request to the
  129. service root.
  130.  
  131.    >>> def get_testdata(filename):
  132.    ...     return pkg_resources.resource_string(
  133.    ...         'wadllib.tests.data', filename + '.json')
  134.  
  135.    >>> def bind_to_testdata(resource, filename):
  136.    ...     return resource.bind(get_testdata(filename), 'application/json')
  137.  
  138. The return value is a new Resource object that's "bound" to that JSON
  139. test data.
  140.  
  141.    >>> bound_service_root = bind_to_testdata(service_root, 'root')
  142.    >>> sorted(bound_service_root.parameter_names())
  143.    ['bugs_collection_link', 'people_collection_link']
  144.    >>> [method.id for method in bound_service_root.method_iter]
  145.    ['service-root-get']
  146.  
  147.  
  148. Now the bound resource object has a JSON representation, and now
  149. 'people_collection_link' makes sense. We can follow the
  150. 'people_collection_link' to a new Resource object.
  151.  
  152.    >>> link_parameter = bound_service_root.get_parameter(link_name)
  153.    >>> link_parameter.style
  154.    'plain'
  155.    >>> link_parameter.get_value()
  156.    u'http://api.launchpad.dev/beta/people'
  157.    >>> personset_resource = link_parameter.linked_resource
  158.    >>> personset_resource.__class__
  159.    <class 'wadllib.application.Resource'>
  160.    >>> personset_resource.url
  161.    u'http://api.launchpad.dev/beta/people'
  162.    >>> personset_resource.type_url
  163.    'http://api.launchpad.dev/beta/#people'
  164.  
  165. This new resource is a collection of people.
  166.  
  167.    >>> personset_resource.id
  168.    'people'
  169.  
  170. The "collection of people" resource supports a standard GET request as
  171. well as a special GET and an overloaded POST. The get_method() method
  172. is used to retrieve WADL definitions of the possible HTTP requests you
  173. might make. Here's how to get the WADL definition of the standard GET
  174. request.
  175.  
  176.    >>> get_method = personset_resource.get_method('get')
  177.    >>> get_method.id
  178.    'people-get'
  179.  
  180. The method name passed into get_method() is treated case-insensitively.
  181.  
  182.    >>> personset_resource.get_method('GET').id
  183.    'people-get'
  184.  
  185. To invoke the special GET request, the client sets the 'ws.op' query
  186. parameter to the fixed string 'find'.
  187.  
  188.    >>> find_method = personset_resource.get_method(
  189.    ...     query_params={'ws.op' : 'findPerson'})
  190.    >>> find_method.id
  191.    'people-findPerson'
  192.  
  193. Given an end-user's values for the non-fixed parameters, it's possible
  194. to get the URL that should be used to invoke the method.
  195.  
  196.    >>> find_method.build_request_url(text='foo')
  197.    u'http://api.launchpad.dev/beta/people?text=foo&ws.op=findPerson'
  198.  
  199.    >>> find_method.build_request_url({'ws.op' : 'findPerson', 'text' : 'bar'})
  200.    u'http://api.launchpad.dev/beta/people?text=bar&ws.op=findPerson'
  201.  
  202. An error occurs if the end-user gives an incorrect value for a fixed
  203. parameter value, or omits a required parameter.
  204.  
  205.    >>> find_method.build_request_url()
  206.    Traceback (most recent call last):
  207.    ...
  208.    ValueError: No value for required parameter 'text'
  209.  
  210.    >>> find_method.build_request_url(
  211.    ...     {'ws.op' : 'findAPerson', 'text' : 'foo'})
  212.    ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
  213.    Traceback (most recent call last):
  214.    ...
  215.    ValueError: Value 'findAPerson' for parameter 'ws.op' conflicts
  216.    with fixed value 'findPerson'
  217.  
  218. To invoke the overloaded POST request, the client sets the 'ws.op'
  219. query variable to the fixed string 'newTeam':
  220.  
  221.    >>> create_team_method = personset_resource.get_method(
  222.    ...     'post', representation_params={'ws.op' : 'newTeam'})
  223.    >>> create_team_method.id
  224.    'people-newTeam'
  225.  
  226. findMethod() returns None when there's no WADL method matching the
  227. name or the fixed parameters.
  228.  
  229.    >>> print personset_resource.get_method('nosuchmethod')
  230.    None
  231.  
  232.    >>> print personset_resource.get_method(
  233.    ...     'post', query_params={'ws_op' : 'nosuchparam'})
  234.    None
  235.  
  236. Let's say the browser makes a GET request to the person set resource
  237. and gets back a representation. We can bind that representation to our
  238. description of the person set resource.
  239.  
  240.    >>> bound_personset = bind_to_testdata(personset_resource, 'personset')
  241.    >>> bound_personset.get_parameter("start").get_value()
  242.    0
  243.    >>> bound_personset.get_parameter("total_size").get_value()
  244.    63
  245.  
  246. We can keep following links indefinitely, so long as we bind to a
  247. representation to each resource as we get it, and use the
  248. representation to find the next link.
  249.  
  250.    >>> next_page_link = bound_personset.get_parameter("next_collection_link")
  251.    >>> next_page_link.get_value()
  252.    u'http://api.launchpad.dev/beta/people?ws.start=5&ws.size=5'
  253.    >>> page_two = next_page_link.linked_resource
  254.    >>> bound_page_two = bind_to_testdata(page_two, 'personset-page2')
  255.    >>> bound_page_two.url
  256.    u'http://api.launchpad.dev/beta/people?ws.start=5&ws.size=5'
  257.    >>> bound_page_two.get_parameter("start").get_value()
  258.    5
  259.    >>> bound_page_two.get_parameter("next_collection_link").get_value()
  260.    u'http://api.launchpad.dev/beta/people?ws.start=10&ws.size=5'
  261.  
  262. Let's say the browser makes a POST request that invokes the 'newTeam'
  263. named operation. The response will include a number of HTTP headers,
  264. including 'Location', which points the way to the newly created team.
  265.  
  266.    >>> headers = { 'Location' : 'http://api.launchpad.dev/~newteam' }
  267.    >>> response = create_team_method.response.bind(headers)
  268.    >>> location_parameter = response.get_parameter('Location')
  269.    >>> location_parameter.get_value()
  270.    'http://api.launchpad.dev/~newteam'
  271.    >>> new_team = location_parameter.linked_resource
  272.    >>> new_team.url
  273.    'http://api.launchpad.dev/~newteam'
  274.    >>> new_team.type_url
  275.    'http://api.launchpad.dev/beta/#team'
  276.  
  277. ======================
  278. Resource instantiation
  279. ======================
  280.  
  281. If you happen to have the URL to an object lying around, and you know
  282. its type, you can construct a Resource object directly instead of
  283. by following links.
  284.  
  285.    >>> from wadllib.application import Resource
  286.    >>> limi_person = Resource(wadl, "http://api.launchpad.dev/beta/~limi",
  287.    ...     "http://api.launchpad.dev/beta/#person")
  288.    >>> sorted([method.id for method in limi_person.method_iter])[:3]
  289.    ['person-acceptInvitationToBeMemberOf', 'person-addMember', 'person-declineInvitationToBeMemberOf']
  290.  
  291.    >>> bound_limi = bind_to_testdata(limi_person, 'person-limi')
  292.    >>> sorted(bound_limi.parameter_names())[:3] # doctest: +NORMALIZE_WHITESPACE
  293.    ['admins_collection_link', 'confirmed_email_addresses_collection_link',
  294.     'date_created']
  295.    >>> languages_link = bound_limi.get_parameter("languages_collection_link")
  296.    >>> languages_link.get_value()
  297.    u'http://api.launchpad.dev/beta/~limi/languages'
  298.  
  299. You can bind a Resource to a representation when you create it.
  300.  
  301.    >>> limi_data = get_testdata('person-limi')
  302.    >>> bound_limi = Resource(
  303.    ...     wadl, "http://api.launchpad.dev/beta/~limi",
  304.    ...     "http://api.launchpad.dev/beta/#person", limi_data,
  305.    ...     "application/json")
  306.    >>> bound_limi.get_parameter("languages_collection_link").get_value()
  307.    u'http://api.launchpad.dev/beta/~limi/languages'
  308.  
  309. By default the representation is treated as a string and processed
  310. according to the media type you pass into the Resource constructor. If
  311. you've already processed the representation, pass in False for the
  312. 'representation_needs_processing' argument.
  313.  
  314.    >>> import simplejson
  315.    >>> processed_limi_data = simplejson.loads(unicode(limi_data))
  316.    >>> bound_limi = Resource(wadl, "http://api.launchpad.dev/beta/~limi",
  317.    ...     "http://api.launchpad.dev/beta/#person", processed_limi_data,
  318.    ...     "application/json", False)
  319.    >>> bound_limi.get_parameter("languages_collection_link").get_value()
  320.    u'http://api.launchpad.dev/beta/~limi/languages'
  321.  
  322. Most of the time, the representation of a resource is of the type
  323. you'd get by sending a standard GET to that resource. If that's not
  324. the case, you can specify a RepresentationDefinition as the
  325. 'representation_definition' argument to bind() or the Resource
  326. constructor, to show what the representation really looks like. Here's
  327. an example.
  328.  
  329. There's a method on a person resource such as bound_limi that's
  330. identified by a distinctive query argument: ws.op=getMembersByStatus.
  331.  
  332.    >>> method = bound_limi.get_method(
  333.    ...     query_params={'ws.op' : 'findPathToTeam'})
  334.  
  335. Invoke this method with a GET request and you'll get back a page from
  336. a list of people.
  337.  
  338.    >>> people_page_repr_definition = (
  339.    ...     method.response.get_representation_definition('application/json'))
  340.    >>> people_page_repr_definition.tag.attrib['href']
  341.    'http://api.launchpad.dev/beta/#person-page'
  342.  
  343. As it happens, we have a page from a list of people to use as test data.
  344.  
  345.    >>> people_page_repr = get_testdata('personset')
  346.  
  347. If we bind the resource to the result of the method invocation as
  348. happened above, we don't be able to access any of the parameters we'd
  349. expect. wadllib will think the representation is of type
  350. 'person-full', the default GET type for bound_limi.
  351.  
  352.    >>> bad_people_page = bound_limi.bind(people_page_repr)
  353.    >>> print bad_people_page.get_parameter('total_size')
  354.    None
  355.  
  356. Since we don't actually have a 'person-full' representation, we won't
  357. be able to get values for the parameters of that kind of
  358. representation.
  359.  
  360.    >>> bad_people_page.get_parameter('name').get_value()
  361.    Traceback (most recent call last):
  362.    ...
  363.    KeyError: 'name'
  364.  
  365. So that's a dead end. *But*, if we pass the correct representation
  366. type into bind(), we can access the parameters associated with a
  367. 'person-page' representation.
  368.  
  369.    >>> people_page = bound_limi.bind(
  370.    ...     people_page_repr,
  371.    ...     representation_definition=people_page_repr_definition)
  372.    >>> people_page.get_parameter('total_size').get_value()
  373.    63
  374.  
  375. If you invoke the method and ask for a media type other than JSON, you
  376. won't get anything.
  377.  
  378.    >>> print method.response.get_representation_definition('text/html')
  379.    None
  380.  
  381. Data type conversion
  382. ====================
  383.  
  384. The values of date and dateTime parameters are automatically converted to
  385. Python datetime objects.
  386.  
  387.    >>> data_type_wadl = application_for('data-types-wadl.xml')
  388.    >>> service_root = data_type_wadl.get_resource_by_path('')
  389.  
  390.    >>> representation = simplejson.dumps(
  391.    ...     {'a_date': '2007-10-20',
  392.    ...      'a_datetime': '2005-06-06T08:59:51.619713+00:00'})
  393.    >>> bound_root = service_root.bind(representation, 'application/json')
  394.  
  395.    >>> bound_root.get_parameter('a_date').get_value()
  396.    datetime.datetime(2007, 10, 20, 0, 0)
  397.    >>> bound_root.get_parameter('a_datetime').get_value() # doctest: +ELLIPSIS
  398.    datetime.datetime(2005, 6, 6, 8, ...)
  399.  
  400. A 'date' field can include a timestamp, and a 'datetime' field can
  401. omit one. wadllib will turn both into datetime objects.
  402.  
  403.    >>> representation = simplejson.dumps(
  404.    ...     {'a_date': '2005-06-06T08:59:51.619713+00:00',
  405.    ...      'a_datetime': '2007-10-20'})
  406.    >>> bound_root = service_root.bind(representation, 'application/json')
  407.  
  408.    >>> bound_root.get_parameter('a_datetime').get_value()
  409.    datetime.datetime(2007, 10, 20, 0, 0)
  410.    >>> bound_root.get_parameter('a_date').get_value() # doctest: +ELLIPSIS
  411.    datetime.datetime(2005, 6, 6, 8, ...)
  412.  
  413. If a date or dateTime parameter has a null value, you get None. If the
  414. value is a string that can't be parsed to a datetime object, you get a
  415. ValueError.
  416.  
  417.    >>> representation = simplejson.dumps(
  418.    ...     {'a_date': 'foo', 'a_datetime': None})
  419.    >>> bound_root = service_root.bind(representation, 'application/json')
  420.    >>> bound_root.get_parameter('a_date').get_value()
  421.    Traceback (most recent call last):
  422.    ...
  423.    ValueError: foo
  424.    >>> print bound_root.get_parameter('a_datetime').get_value()
  425.    None
  426.  
  427. =======================
  428. Representation creation
  429. =======================
  430.  
  431. You must provide a representation when invoking certain methods. The
  432. representation() method helps you build one without knowing the
  433. details of how a representation is put together.
  434.  
  435.    >>> create_team_method.build_representation(
  436.    ...     display_name='Joe Bloggs', name='joebloggs')
  437.    ('application/x-www-form-urlencoded', 'display_name=Joe+Bloggs&ws.op=newTeam&name=joebloggs')
  438.  
  439. The return value of build_representation is a 2-tuple containing the
  440. media type of the built representation, and the string representation
  441. itself. Along with the resource's URL, this is all you need to send
  442. the representation to a web server.
  443.  
  444.    >>> bound_limi.get_method('patch').build_representation(name='limi2')
  445.    ('application/json', '{"name": "limi2"}')
  446.  
  447. Representations may require values for certain parameters.
  448.  
  449.    >>> create_team_method.build_representation()
  450.    Traceback (most recent call last):
  451.    ...
  452.    ValueError: No value for required parameter 'display_name'
  453.  
  454.    >>> bound_limi.get_method('put').build_representation(name='limi2')
  455.    Traceback (most recent call last):
  456.    ...
  457.    ValueError: No value for required parameter 'mugshot_link'
  458.  
  459. Some representations may safely include binary data.
  460.  
  461.    >>> binary_stream = pkg_resources.resource_stream(
  462.    ...     'wadllib.tests.data', 'multipart-binary-wadl.xml')
  463.    >>> binary_wadl = Application(
  464.    ...     "http://www.example.com/", binary_stream)
  465.    >>> service_root = binary_wadl.get_resource_by_path('')
  466.  
  467.    >>> method = service_root.get_method('post', 'multipart/form-data')
  468.    >>> media_type, doc = method.build_representation(
  469.    ...     text_field="text", binary_field="\x01\x02")
  470.    >>> print media_type
  471.    multipart/form-data; boundary=...
  472.    >>> print doc
  473.    MIME-Version: 1.0
  474.    Content-Type: multipart/form-data; boundary="..."
  475.    <BLANKLINE>
  476.    --...
  477.    Content-Type: text/plain; charset="utf-8"
  478.    MIME-Version: 1.0
  479.    Content-Disposition: form-data; name="text_field"
  480.    <BLANKLINE>
  481.    text
  482.    --...
  483.    Content-Type: application/octet-stream
  484.    MIME-Version: 1.0
  485.    Content-Disposition: form-data; name="binary_field"
  486.    <BLANKLINE>
  487.    ...
  488.    --...
  489.    >>> '\x01\x02' in doc
  490.    True
  491.  
  492.    >>> method = service_root.get_method('post', 'text/unknown')
  493.    >>> method.build_representation(field="value")
  494.    Traceback (most recent call last):
  495.    ...
  496.    ValueError: Unsupported media type: 'text/unknown'
  497.  
  498. =======
  499. Options
  500. =======
  501.  
  502. Some parameters take values from a predefined list of options.
  503.  
  504.    >>> option_wadl = application_for('options-wadl.xml')
  505.    >>> definitions = option_wadl.representation_definitions
  506.    >>> service_root = option_wadl.get_resource_by_path('')
  507.    >>> definition = definitions['service-root-json']
  508.    >>> param = definition.params(service_root)[0]
  509.    >>> print param.name
  510.    has_options
  511.    >>> sorted([option.value for option in param.options])
  512.    ['Value 1', 'Value 2']
  513.  
  514. Such parameters cannot take values that are not in the list.
  515.  
  516.    >>> definition.validate_param_values(
  517.    ...     [param], {'has_options': 'Value 1'})
  518.    {'has_options': 'Value 1'}
  519.  
  520.    >>> definition.validate_param_values(
  521.    ...     [param], {'has_options': 'Invalid value'})
  522.    Traceback (most recent call last):
  523.    ...
  524.    ValueError: Invalid value 'Invalid value' for parameter
  525.    'has_options': valid values are: "Value 1", "Value 2"
  526.  
  527.  
  528. ================
  529. Error conditions
  530. ================
  531.  
  532. You'll get None if you try to look up a nonexistent resource.
  533.  
  534.    >>> print wadl.get_resource_by_path('nosuchresource')
  535.    None
  536.  
  537. You'll get an exception if you try to look up a nonexistent resource
  538. type.
  539.  
  540.    >>> print wadl.get_resource_type('#nosuchtype')
  541.    Traceback (most recent call last):
  542.    KeyError: 'No such XML ID: "#nosuchtype"'
  543.  
  544. You'll get None if you try to look up a method whose parameters don't
  545. match any defined method.
  546.  
  547.    >>> print bound_limi.get_method(
  548.    ...     'post', representation_params={ 'foo' : 'bar' })
  549.    None
  550.  
  551. .. toctree::
  552.    :glob:
  553.  
  554.    *
  555.    docs/*
  556.